import { configureStore, createSlice } from '@reduxjs/toolkit';
import { isObject } from '../common/tool';
import { store } from './store';
import { setUserinfo } from './user-info';
import Taro from "@tarojs/taro";
import { setStaticState } from './static-store'

/**
 * YLGY
 */
export const YLGY = createSlice({
  name: 'YLGY',
  initialState: {
    data: {},
  },
  reducers: {
    setData: (state, data) => {
      state.data = {...state.data, ...data};
    },
    getState: state => state
  }
})
/**
 * SIORE
 */
export const STORE = configureStore({
  reducer: YLGY.reducer
})
/**
 * 全局 store
 */
export const allStore = configureStore({
  reducer: {
    YLGY: YLGY.reducer
  }
})
export const initSystemInfo = () => {
  const systeminfo = Taro.getSystemInfoSync();
  setStaticState('systemInfo', systeminfo);
  setStaticState('isSizeScreen', (systeminfo.screenHeight / systeminfo.screenWidth)  > 2 ? false : true);
  setStaticState('RP', (systeminfo.screenHeight / systeminfo.screenWidth));
  setStaticState('oneRpx', (systeminfo.screenWidth / 750));
}
export const login = () => {
  Taro.login(({
    success(res){
      setStaticState('login', res);
    },
    fail(res){
      console.log(res);
    }
  }))
};
export const getUserInfo = () => {
  const userInfo  = Taro.getStorageSync('user-info');
  if (isObject(userInfo)) {
    store.dispatch(setUserinfo({userInfo: userInfo}));
    Object.keys(userInfo).forEach(key => setStaticState(key, userInfo[key]));
    Object.keys(userInfo.userInfo).forEach(key => setStaticState(key, userInfo.userInfo));
    return;
  }
  Taro.showModal({
    title: '获取用户信息',
    content: '欢迎进入哲趣小助手，获取你的微信头像和用户名用于更好的体验。',
    success(res){
      try{
        if (res.confirm) {
          Taro.getUserProfile({
            desc: '获取用户名和头像',
            fail(res){
              Taro.showModal({
                'title': '失败身份验证拒绝',
                success() {
                  Taro.exitMiniProgram();
                }
              });
            },
            success(res) {
              Object.keys(res).forEach(key => setStaticState(key, res[key]));
              Object.keys(res.userInfo).forEach(key => setStaticState(key, res?.userInfo?.[key]));
              store.dispatch(setUserinfo({userInfo: res}));
              Taro.setStorageSync('user-info', res);
            }
          });
        };
        if (res.cancel) {
          Taro.exitMiniProgram();
        }
      } catch (err) {
        Taro.showModal({
          'title': '失败身份验证拒绝',
          success() {
            Taro.exitMiniProgram();
          }
        });
      }

    }
  })

};

